/*
 * @Author: szx
 * @Date: 2022-02-27 14:17:46
 * @LastEditTime: 2022-02-27 14:32:33
 * @Description:
 * @FilePath: \leetcode\100-199\151\151_2.js
 */
/**
 * @param {string} s
 * @return {string}
 */

var reverseWords = function (s) {
    const arr = Array.from(s);
    removeExtraSpaces(arr);
    reverse(arr, 0, arr.length - 1);
    let l = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == ' ') {
            reverse(arr, l, i - 1);
            l = i + 1;
        }
    }
    reverse(arr, l, arr.length - 1);
    return arr.join('');
};
const reverse = function (arr, l, r) {
    while (l < r) {
        const tmp = arr[l];
        arr[l++] = arr[r];
        arr[r--] = tmp;
    }
};

function removeExtraSpaces(arr) {
    let cur = 0;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == ' ' && (i == 0 || arr[i - 1] == ' ')) continue;
        arr[cur++] = arr[i];
    }
    arr.length = arr[cur - 1] === ' ' ? cur - 1 : cur;
}

console.log('1' + reverseWords('"  hello world  "') + '2');
console.log('1' + reverseWords('  the   sky is   blue  ') + '2');
